﻿(function (ko, datacontext) {

    datacontext.Section = Section;
    datacontext.Note = Note;

    ko.dirtyFlag = function (root, isInitiallyDirty) {
        var result = function () { }
        var _initialState = ko.observable(ko.toJSON(root));
        var _isInitiallyDirty = ko.observable(isInitiallyDirty);

        result.isDirty = ko.computed(function () {
            return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
        });

        result.reset = function () {
            _initialState(ko.toJSON(root));
            _isInitiallyDirty(false);
        };
        return result;
    };


    ko.orgNoteVal = function (title, desc) {
        return { title: ko.observable(title), desc: ko.observable(desc) }; 
    };

  

    function Section(data) {
        var self = this;
        data = data || {};

        // Persisted properties
        self.SectionID = data.SectionID;
        self.Title = ko.observable(data.Title);
        self.Summary = ko.observable(data.Summary);
        self.Description = ko.observable(data.Description);
        self.SortIndex = ko.observable(data.SortIndex);
        self.NoteID = data.NoteID;
        self.IsEditingListTitle = ko.observable(false);
    

        // Non-persisted properties
        self.ErrorMessage = ko.observable();
        self.dirtyFlag = new ko.dirtyFlag(self);
        self.save = function () { return datacontext.saveChangedSection(self); };    
      
        //persist edits to real values on accept
        self.acceptDescription = function () {
            this.Description($('.htmlEditor').prev().find('.nicEdit-main').html());
            window.noteApp.noteViewModel.selectedSection("");
        }.bind(this);

        //reset to originals on cancel
        self.cancelDescription = function () {
            window.noteApp.noteViewModel.selectedSection("");
        }.bind(this);

        // Auto-save when these properties change
        //self.IsDone.subscribe(self.save);
        //self.Title.subscribe(self.save);
    };

    function Note(data) {
        var self = this;
        data = data || {};

        // Persisted properties
        self.NoteID = data.NoteID;      
        self.Title = ko.observable(data.Title || "Title...");
        self.Description = ko.observable(data.Description || "");
        self.SortIndex = ko.observable(data.SortIndex || 0);
        self.NoteTypeID = ko.observable(data.NoteTypeID || 1); //default 1 
        self.IsEditingListTitle = ko.observable(false);
        self.ColorCode = ko.observable(data.ColorCode || "#D4FCFC");


        self.themes = config.themes;
        //self.BoardUrl = ko.observable(data.BoardUrl);
        //self.UserName = ko.observable(data.UserName);
        var arrSection = importSections(data.Sections);
        self.Sections = ko.observableArray(arrSection);

        self.allowToAddSection = ko.computed(function () {
            if (config.ts == 0 || self.Sections().length < config.ts) { return true; }
            else { return false; }
        });

         // Non-persisted properties
        //self.dirtyFlag = new ko.dirtyFlag(self);

        self.orgVal = new ko.orgNoteVal(self.Title(), self.Description());

       
       
        self.NewTodoTitle = ko.observable("SubTitle...");
        self.ErrorMessage = ko.observable();
      
        //a list of the currently dirty items
        self.dirtyItems = ko.computed(function () {
            return ko.utils.arrayFilter(self.Sections(), function (section) {
                return section.dirtyFlag.isDirty();
            });
        });
        //For Note Dirty
        self.isNoteDirty =  ko.computed(function () {
            return self.Title() !== self.orgVal.title() || self.Description() !== self.orgVal.desc();
        }); 
        //For Section Dirty
        self.isDirty = ko.computed(function () {
            return self.dirtyItems().length > 0 || self.isNoteDirty;
        });
        //to reset note after saving
        self.resetNote = function () {
            var items = self.dirtyItems();
            for (var i = 0; i < items.length; i++) {                
                items[i].dirtyFlag.reset();
            }
            self.orgVal.title(self.Title());
            self.orgVal.desc( self.Description());
        }

        self.undoNote = function () {
            var items = self.dirtyItems();
            for (var i = 0; i < items.length; i++) {
                items[i].dirtyFlag.reset();
            }
            self.Title(self.orgVal.title());
            self.Description(self.orgVal.desc());
        }


        self.save = function () { return datacontext.saveChangedNote(self); };

        self.addSection = function () {
           // var self = this;
            if (self.NewTodoTitle()) { // need a title to save
                var section = datacontext.createSection(
                    {
                        Title: self.NewTodoTitle(),
                        Summary: "Summary...",
                        NoteID: self.NoteID
                    });
                self.Sections.push(section);
                datacontext.saveNewSection(section);
                section.IsEditingListTitle(true);
            }
        }; 

        self.saveSection = function () {         
            datacontext.saveChangedNote(self);            
        }; 

        self.saveCustomNote = function(item, event) {
            var $this = $(event.target);
            self.Description($this.parents('article').find('.noteDesc').html());
            datacontext.saveChangedNote(self);
        };

        self.deleteSection = function () {
            var section = this;
            return datacontext.deleteSection(section)
                 .done(function () { self.Sections.remove(section); });
        };

        self.changeTheme = function () {
            var theme = this;
            return datacontext.changeTheme(self.NoteID,theme.ThemeID )
             .done(function () { self.ColorCode(theme.ColorCode); })
             .fail (function(){self.ErrorMessage('unable to save new theme') });
        }

        // Auto-save when these properties change
        //self.Title.subscribe(self.save);
        self.isDirty.subscribe(function (isDirt) {
            $('.content').masonry('reload');
        });
    };
    // convert raw todoItem data objects into array of Sections
    function importSections(sections) {
        return $.map(sections || [],
                function (section) {
                    return datacontext.createSection(section);
                });
    }


})(ko, noteApp.datacontext);
